<template>
  <div class="image-list-container">
    <el-card class="header-card">
      <div class="header-info">
        <div class="title">
          <el-page-header @back="goBack" :content="categoryName + '图片列表'"></el-page-header>
        </div>
        <div class="actions">
          <el-button type="primary" icon="el-icon-plus" @click="handleUpload">上传图片</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="selectedImages.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="content-card">
      <div v-loading="loading">
        <el-checkbox-group v-model="selectedImages" class="image-list">
          <div v-for="item in imageList" :key="item.id" class="image-item">
            <el-checkbox :label="item.id" class="image-checkbox"></el-checkbox>
            <div class="image-wrapper">
              <el-image 
                :src="item.url" 
                fit="cover"
                :preview-src-list="[item.url]"
              ></el-image>
              <div class="image-info">
                <div class="image-title">{{ item.name }}</div>
                <div class="image-actions">
                  <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="handleEdit(item)"></el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="handleDelete(item)"></el-button>
                  <el-button type="success" size="mini" icon="el-icon-copy-document" circle @click="copyUrl(item.url)"></el-button>
                </div>
              </div>
            </div>
          </div>
          <div v-if="imageList.length === 0" class="empty-tip">
            <el-empty description="暂无图片"></el-empty>
          </div>
        </el-checkbox-group>

        <!-- 分页区域 -->
        <div class="pagination" v-if="imageList.length > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.current"
            :page-sizes="[12, 24, 48, 96]"
            :page-size="pageParams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 上传图片对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="uploadDialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入图片名称"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <el-upload
            class="image-uploader"
            action="#"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.url" :src="form.url" class="uploaded-image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" placeholder="请输入排序"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入图片描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ImageList',
  data() {
    return {
      categoryId: null,
      categoryName: '',
      categoryCode: '',
      // 分页参数
      pageParams: {
        current: 1,
        size: 24
      },
      // 图片列表
      imageList: [],
      total: 0,
      loading: false,
      selectedImages: [],
      // 上传对话框
      uploadDialogVisible: false,
      dialogTitle: '上传图片',
      // 表单数据
      form: {
        id: null,
        name: '',
        url: '',
        categoryId: null,
        description: '',
        sort: 0
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入图片名称', trigger: 'blur' }],
        url: [{ required: true, message: '请上传图片', trigger: 'change' }]
      }
    }
  },
  created() {
    this.categoryId = parseInt(this.$route.params.categoryId)
    this.categoryName = this.$route.query.categoryName || '未知分类'
    this.categoryCode = this.$route.query.categoryCode || ''
    this.fetchData()
  },
  methods: {
    // 获取图片列表
    fetchData() {
      this.loading = true;
      request({
        url: '/car-vehicle/image/page',
        method: 'get',
        params: {
          current: this.pageParams.current,
          size: this.pageParams.size,
          categoryId: this.categoryId,
          name: this.searchForm ? this.searchForm.name : ''
        }
      }).then(res => {
        if (res.code === 200) {
          this.imageList = res.data.records;
          this.total = res.data.total;
        } else {
          this.$message.error(res.message || '获取图片列表失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 返回上一页
    goBack() {
      this.$router.push('/image-categories');
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current;
      this.fetchData();
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size;
      this.pageParams.current = 1;
      this.fetchData();
    },
    // 处理上传图片
    handleUpload() {
      this.dialogTitle = '上传图片';
      this.form = {
        id: null,
        name: '',
        url: '',
        categoryId: this.categoryId,
        description: '',
        sort: 0
      };
      this.uploadDialogVisible = true;
    },
    // 处理编辑图片
    handleEdit(item) {
      this.dialogTitle = '编辑图片';
      this.form = { ...item };
      this.uploadDialogVisible = true;
    },
    // 处理删除图片
    handleDelete(item) {
      this.$confirm('确认删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/car-vehicle/image/${item.id}`,
          method: 'delete'
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        });
      }).catch(() => {});
    },
    // 处理批量删除
    handleBatchDelete() {
      if (this.selectedImages.length === 0) {
        this.$message.warning('请选择要删除的图片');
        return;
      }
      this.$confirm(`确认删除选中的${this.selectedImages.length}张图片?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/car-vehicle/image/batch',
          method: 'delete',
          data: this.selectedImages
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('批量删除成功');
            this.selectedImages = [];
            this.fetchData();
          } else {
            this.$message.error(res.message || '批量删除失败');
          }
        });
      }).catch(() => {});
    },
    // 复制图片URL
    copyUrl(url) {
      const input = document.createElement('input');
      input.value = url;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.$message.success('图片URL已复制到剪贴板');
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const method = this.form.id ? 'put' : 'post';
          request({
            url: '/car-vehicle/image',
            method,
            data: this.form
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.form.id ? '更新' : '上传'}成功`);
              this.uploadDialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(res.message || `${this.form.id ? '更新' : '上传'}失败`);
            }
          });
        } else {
          return false;
        }
      });
    },
    // 图片上传前处理
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.form.url = res.data.url
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败：' + res.message)
      }
    },
    // 自定义上传方法
    customUpload(event) {
      const file = event.file;
      const formData = new FormData();
      formData.append('file', file);

      request({
        url: '/car-integration/files/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === 200) {
          this.handleImageSuccess(res, file);
        } else {
          this.$message.error('上传失败：' + res.message);
        }
      }).catch(() => {
        this.$message.error('上传失败');
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.image-list-container {
  padding: 20px;
  
  .header-card {
    margin-bottom: 20px;
    
    .header-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: bold;
      }
      
      .actions {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
  
  .content-card {
    .image-list {
      display: flex;
      flex-wrap: wrap;
      margin: -10px;
      
      .image-item {
        width: calc(25% - 20px);
        margin: 10px;
        position: relative;
        
        @media screen and (max-width: 1400px) {
          width: calc(33.33% - 20px);
        }
        
        @media screen and (max-width: 992px) {
          width: calc(50% - 20px);
        }
        
        @media screen and (max-width: 576px) {
          width: calc(100% - 20px);
        }
        
        .image-checkbox {
          position: absolute;
          top: 10px;
          left: 10px;
          z-index: 2;
        }
        
        .image-wrapper {
          border-radius: 4px;
          overflow: hidden;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          
          .el-image {
            width: 100%;
            height: 200px;
            display: block;
          }
          
          .image-info {
            padding: 10px;
            background-color: #fff;
            
            .image-title {
              font-size: 14px;
              margin-bottom: 10px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .image-actions {
              display: flex;
              justify-content: flex-end;
              
              .el-button {
                margin-left: 5px;
              }
            }
          }
        }
      }
    }
    
    .empty-tip {
      padding: 30px 0;
    }
    
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 300px;
    height: 200px;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 200px;
      line-height: 200px;
      text-align: center;
    }
    
    .uploaded-image {
      width: 300px;
      height: 200px;
      display: block;
      object-fit: cover;
    }
  }
}
</style> 